import random
import urllib

import random
import time

import requests
import simplejson
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils.timezone import now
from django.views.decorators.csrf import csrf_exempt

from server.models import db_cp


@csrf_exempt
def cp_insert(request):
    print(request)
    body = (request.body).decode()
    body_json = eval(urllib.parse.unquote(body))
    listRes = body_json['wer']
    db_cp(list=listRes, create=now(), update=now()).save()
    return JsonResponse({'data': True})


@csrf_exempt
def cp_get(request):
    res = db_cp.objects.all().order_by('-id')[0]
    back = {'list': eval(res.list), 'time': res.create.strftime('%Y-%m-%d %H:%M:%S')}
    print(back)
    return simplejson.dumps(back)

@csrf_exempt
def run(request):
    red = [i for i in range(1, 34)]
    blue = [i for i in range(1, 17)]

    def roll(red, blue):
        red_res = sorted(random.sample(red, 6))
        blue_res = random.sample(blue, 1)
        red_res.append(blue_res[0])
        return red_res

    resdsd = [
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
    ]
    all = [
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
    ]
    print('begin', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    syscNum = 2000000000
    for i in range(syscNum):
        res = roll(red, blue)
        if res[:-1] not in all[res[-1] - 1]:
            all[res[-1] - 1].append(res[:-1])
            res.append(1)
            resdsd[res[-2] - 1].append(res)
        else:
            index = all[res[-1] - 1].index(res[:-1])
            resdsd[res[-1] - 1][index][-1] += 1

    def takeSecond(elem):
        return elem[-1]

    last = []
    for item in resdsd:
        item.sort(key=takeSecond)
        last.extend(item[:10])
        print(item[:10])

    last.sort(key=takeSecond)
    print(last[:10])

    print('end', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    print(requests.post(url='http://superqa.com.cn:9092/cp/insert',
                        json={'wer': last[:10]}).json())